import axios from 'axios';
import {
  getLocalStorage
} from '@/utils/localstore';
import {
  Message
} from 'element-ui';

const notWariing = ['file/page', 'linker/list'];
const pending = [];

const removePending = (config) => {
  for (const key in pending) {
    if (Object.prototype.hasOwnProperty.call(pending, key)) {
      const item = +key;
      const list = pending[key];
      if (list.url === config.url && list.method === config.method && JSON.stringify(list.params) === JSON.stringify(config.params) && JSON.stringify(list.data) === JSON.stringify(config.data)) {
        list.cancel('操作太频繁，请稍后再试');
        pending.splice(item, 1);
      }
    }
  }
};

const instance = axios.create({
  timeout: 8000000
});

instance.interceptors.request.use(
  (config) => {
    removePending(config);
    if (getLocalStorage('adminToken')) {
      config.headers['Token'] = getLocalStorage('adminToken');
    }
    return config;
  },

  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  async(response) => {
    removePending(response.config);
    const {
      data
    } = response;
    if (!data.success) {
      if (data.message || data.detail) {
        const {
          request: {
            responseURL
          }
        } = response;
        const notWarning = notWariing.some(item => {
          return item.includes(responseURL);
        });
        if (!notWarning) {
          // 刚登录进入主页时就报警告的问题
          setTimeout(() => {
            Message.warning(`${data.message && data.message} ${data.detail && data.detail}`);
          }, 300);
        }
      }
    }
    return response.data;
  },

  (error) => {
    // const confirm = window.confirm('网络连接失败');
    // if(confirm){
    // clearLocalStorage();
    // window.location.reload();
    // }
    Message.error('网络错误');
    return Promise.reject(error);
  }
);

export default instance;
